﻿var currentChannelName = '#no_channel_selected_yet';
var maxMessagesCount = 10;

function body_onload() {

    updateChannelNamesFromService();
    updateMessagesFromChannelToSectionArticle(); 

    setInterval("updateChannelNamesFromService()", 3000);
}

function updateChannelNamesFromService() {
    
    var serviceUrl = "http://" + document.location.host + "/TwitterService.svc/GetChannelNames"; 
    // var serviceUrl = "../TwitterService.svc/GetChannelNames"; 

    $.ajax(
    {
        async: true,
        type: "GET",
        url: serviceUrl,
        contentType: "application/json;charset=utf-8",
        success: onGetChannelNames_Success
    });    
}

var currentChannelNames = new Array();

function onGetChannelNames_Success(data) {    

    var channelNames = data;

    var aside = $('#channelNames');

    for (var i = 0; i < currentChannelNames.length; i++) {
                          
        if($.inArray(currentChannelNames[i], channelNames) < 0){

            if(currentChannelNames[i] == currentChannelName){
                currentChannelName = '#no_channel_selected_yet';
                $('#sectionArticle').html('');
            }

            // find and remove the div 
            var asideDivs = $('#channelNames>*');
            for (var k = 0; k < asideDivs.length; k++) {                       
                if(asideDivs[k].getAttribute('channelName') == currentChannelNames[i]){
                    asideDivs[k].id = 'temporary_id_for_an_element_to_be_deleted';
                    $('#' + asideDivs[k].id).remove();
                    break;
                }                
            }

            currentChannelNames.splice(i, 1);            
        }
    }

    for (var i = 0; i < channelNames.length; i++) {
            
        if($.inArray(channelNames[i], currentChannelNames) < 0)
        {
            currentChannelNames.push(channelNames[i]);
        
            var newDiv = $('<div></div>');
            newDiv.text('#' + channelNames[i]);
            newDiv.attr('class', 'divChannelName');
            newDiv.attr('channelName', channelNames[i]);

            newDiv.bind('click', divChannelName_click);

            aside.append(newDiv);
        }
    }
}

function divChannelName_click(event) {
    if (document.event) {
        event = document.event;
    }
    
    $('#sectionArticle').html('loading ...');
    currentChannelName = event.target.getAttribute('channelName'); 

    $('#sectionHeader').html('Channel #' + currentChannelName);

    var asideChildren = $('#channelNames>div');

    for (var i = 0; i < asideChildren.length; i++) {
        divChannelName = asideChildren[i];
        if (divChannelName.getAttribute('channelName') != currentChannelName) {
            divChannelName.setAttribute('class', 'divChannelName');            
        }
        else {
            divChannelName.setAttribute('class', 'currentChannel');            
        }
    }    
}

function updateMessagesFromChannelToSectionArticle() {

    if (currentChannelName != '#no_channel_selected_yet') {
        var serviceUrl = "http://" + document.location.host + "/TwitterService.svc/Messages/" + currentChannelName + '/' + maxMessagesCount; 

        $.ajax({
            async: true,
            type: "GET",
            url: serviceUrl,            
            contentType: "application/json;charset=utf-8",
            success: function(data){
                setTimeout(updateMessagesFromChannelToSectionArticle, 200);   
                onGetMessagesForChannel_Success(data);
            },
            error: function(){
                setTimeout(updateMessagesFromChannelToSectionArticle, 200); 
            }
        });
    }
    else
    {
        setTimeout(updateMessagesFromChannelToSectionArticle, 200);
    }
}

function onGetMessagesForChannel_Success(data) {        
    
    if(currentChannelName == '#no_channel_selected_yet') {
        $('#sectionArticle').html('');
        //return;
    }

    if(data == null){
        return;
    }

    if(data.length != 0 && data[0].ChannelName == currentChannelName)
    {        
        updateChatMessages(data);
    }
    else
    {
        if(data.length == 0)
        {
            $('#sectionArticle').html('');
        }
    }
}

//var currentMessageIds = new Array();

function updateChatMessages(messages)
{
    var sectionArticle = $('#sectionArticle');

        //$('#sectionArticle>*').remove();
        $('#sectionArticle').html('');

        for (var i = 0; i < messages.length; i++) {
        
            var newDiv = $('<div></div>');
            var date = new Date(parseInt(messages[i].PostDateTime.substr(6)));
            var hourMinSec = '[' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() + ']';
            newDiv.text(hourMinSec + ' ' + messages[i].MessageContent);
            newDiv.attr('class', 'divMessage'); 
            sectionArticle.append(newDiv);
        }
}

function messageContent_onkeypress(event){

    if(document.event){
        event = document.event;
    }

    if(event.keyCode == 13){ // enter    
        postMessage();
    }
}

function buttonPostMessage_onclick() {
    postMessage();
}

function postMessage() {

    if (currentChannelName != '#no_channel_selected_yet') {

        var messageContent = $('#messageContent').val();
        var message = new Object();

        message.ChannelName = currentChannelName;
        message.MessageContent = messageContent;

        var messageJsoned = JSON.stringify(message);        

        var serviceUrl = "http://" + document.location.host + "/TwitterService.svc/UploadMessageByChannelName";
                
        $.ajax({
            async: true,
            type: "POST",
            url: serviceUrl,
            data: messageJsoned,
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            success: onPostMessage_Success
        });        

        $('#messageContent').val('');
    }
}


function onPostMessage_Success() {    
    //updateChatMessages();    
}

function buttonResetChannel_onclick() {

    if (currentChannelName != '#no_channel_selected_yet') {

        var currentChannelNameJsoned = JSON.stringify(currentChannelName);

        var serviceUrl = "http://" + document.location.host + "/TwitterService.svc/DeleteAllMessagesByChannelName";

        $.ajax({
            async: true,
            type: "POST",
            url: serviceUrl,
            data: currentChannelNameJsoned,
            dataType: "json",
            contentType: "application/json;charset=utf-8",            
        });

         $('#sectionArticle>*').remove();
    }
}


function buttonCreateNewChannel_onclick(){

    var channelName = prompt("Create channel", "new channel name"); 
    if(channelName == null){
        return;
    }    
    
    var channelNameJsoned = JSON.stringify(channelName);
    var serviceUrl = "http://" + document.location.host + "/TwitterService.svc/CreateNewChannel";

    $.ajax({
        async: true,
        type: "POST",
        url: serviceUrl,
        data: channelNameJsoned,
        dataType: "json",
        contentType: "application/json;charset=utf-8", 
        success: onCreateNewChannel_Success,
        error: onCreateNewChannel_Error        
    });
}

function onCreateNewChannel_Success(){    
    updateChannelNamesFromService();
}

function onCreateNewChannel_Error(){    
    alert('Creating new channel failed. May be a channel with the same name already exists?');
}

function buttonDeleteCurrentChannel_onclick(){

    if(currentChannelName != '#no_channel_selected_yet'){        
            
        var channelNameJsoned = JSON.stringify(currentChannelName);
        var serviceUrl = "http://" + document.location.host + "/TwitterService.svc/DeleteChannel";

        $.ajax({
            async: true,
            type: "POST",
            url: serviceUrl,
            data: channelNameJsoned,
            dataType: "json",
            contentType: "application/json;charset=utf-8"
        });
    }
    else
    {
        
    }
}

